from django.shortcuts import redirect
from django.urls import reverse
from django.utils.deprecation import MiddlewareMixin


class AuthenticationMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # 定义不需要登录即可访问的URL
        request.current_user = {
            'id': request.session.get('user_id'),
            'username': request.session.get('username'),
            'email': request.session.get('email'),
            'engineer_id': request.session.get('engineer_id'),
            'department': request.session.get('department'),
            'role': request.session.get('role')
        }
        
        # 新增：直接放行登录和注册页面，不再执行后续检查
        if request.path_info in ['/login/', '/register/','/admin/']:
            return None

        # 优化：仅在需要登录的路径检查用户状态
        if not request.current_user['id']:
            return redirect('/login/')

        # 权限验证：普通用户无权访问用户管理和所有报告
        if request.current_user['role'] == 'user':
            if request.path_info in ['/user_management/', '/all_report_list/']:
                return redirect('/index/')

        return None